<template>
	<view class="mock-panel">
		<!-- 	<a-row style="position: absolute;right:36.5vw;top: 7vh;z-index:99">
			<a-col>
				答题信息
			</a-col>
		</a-row> -->

		<view v-if="showSubmitTips" class="popcontent">
			<view class="popbox">
				<h1 style="text-align: center;color: white;">
					考试确认窗口
				</h1>
				<view class="opeartips">
					<p>操作提示</p>
					<p>你当前答对：{{rightNum}},答错：{{errorNum}},未答：{{quelist.length-rightNum-errorNum }}</p>
					<p>1.点击【确认交卷】，将提交考试成绩，考试结束！</p>
					<p>2.点击【继续考试】，将关闭此窗口，继续考试！</p>
				</view>
				<view style="padding: 24rpx;">
					<button style="margin: 12rpx;padding:6px 12px;color: #000;font-size: 16px;"
						@click="setTestStaticStatus">
						确认交卷
					</button>
					<button style="margin: 12rpx;padding:6px 12px;color: #000;font-size: 16px;"
						@click="showSubmitTips=false">
						继续考试
					</button>
				</view>
			</view>
		</view>

		<view class="test-statistical-jiangjie" v-if="showans">
			<view class="statistical-box-jiangjie">
				<a-row>
					<a-col>
						<a-typography-title :level="5" style="color: #fff;">
							错题学习{{balanceTimer}}
						</a-typography-title>
					</a-col>
				</a-row>
				<a-row type="flex" style="min-height: 40%;background-color: #fff;">
					<a-col :span="24">
						<view class="maxwidth" style="padding: 12rpx;">
							<a-typography-text style="text-align: left;line-height: 66rpx;">
								{{cur_qs_index+1}}. {{quelist[cur_qs_index].q_desc}}
							</a-typography-text>
						</view>

						<view class="maxwidth" v-for="(item,index) in quelist[cur_qs_index].q_struct">
							<view>
								<a-typography-text style="line-height: 44rpx;font-size:18px;">
									{{label[index]}}. {{item.value}}
								</a-typography-text>
							</view>
						</view>

					</a-col>
				</a-row>
				<view class="quesction-img-box" v-if="quelist[cur_qs_index].img && quelist[cur_qs_index].img.length>3">
					<view class="imageshow-box">

						<image :src="`${$cdn}${quelist[cur_qs_index].img}`" style="height:150px;width:300px;"
							mode="aspectFit" />
						<!-- 	<a-image class="imageshow" :src="`${$cdn}${quelist[cur_qs_index].img}`" height="250"
							:preview="true" /> -->
					</view>
				</view>



				<a-row class="close-panel" :justify="'center'" type="flex" :gutter="[8,4]">


					<a-col :span="24">
						<a-row style="width: 100%;height: 200rpx;background-color: #fff;">



							<a-col :span="24">

								<a-typography-text>
									正确答案:
								</a-typography-text>
								<a-tag style="font-size: 24px;padding:12px"
									v-for="(item,index) in textInfo[ quelist[cur_qs_index].q_type].getAns( quelist[cur_qs_index])">
									{{item}}
								</a-tag>


								<a-typography-text>
									你的答案:
								</a-typography-text>

								<a-tag style="font-size: 24px;padding:12px" v-for="(c,e) in getChangeAns()">
									{{c}}
								</a-tag>
							</a-col>

							<a-col :span="24">
								<a-row justify="center">
									<a-col>
										<a-button @click="showans=false">
											继续考试
										</a-button>
									</a-col>
								</a-row>

							</a-col>

						</a-row>
					</a-col>
				</a-row>
			</view>
		</view>

		<view class="test-statistical" v-if="showStatistical">
			<view class="statistical-box">
				<a-row>
				</a-row>
				<a-row>
					<a-typography-text style="color: #2a91fd;">
						试卷提交
					</a-typography-text>
				</a-row>
				<a-divider style="margin:0px;background-color: #2a91fd;"></a-divider>

				<a-row>
					<a-col :span="12">
						<a-row v-for="(item,index) in infolist">
							<a-col :span="24">
								<a-typography-text>
									{{item[0]}}:
								</a-typography-text>
								<a-typography-text style="margin-left: 18rpx">
									<template v-if="item[1]!='gender'">
										<div class="card-box ant-card-bordered">
											{{userinfo[item[1]]}}
										</div>
									</template>
									<template v-else>
										<div class="card-box ant-card-bordered">
											{{genderText[userinfo[item[1]]]}}
										</div>
									</template>
								</a-typography-text>
							</a-col>
						</a-row>
						<a-row>
							<a-col :span="24">
								<a-typography-paragraph>
									总共:<a-typography-text strong style="color:#000000">{{quelist.length}}
									</a-typography-text> 道</a-typography-paragraph>
							</a-col>
							<a-col :span="24">
								<a-typography-paragraph>
									正确:<a-typography-text type="success" strong style="font-size: 42rpx;color:#3f77fa">
										{{rightNum}}
									</a-typography-text> 道</a-typography-paragraph>
							</a-col>
							<a-col :span="24">
								<a-typography-paragraph>
									错误:<a-typography-text type="warning" strong style="font-size: 42rpx;color:#f33333">
										{{errorNum + (quelist.length-rightNum-errorNum)}}
									</a-typography-text> 道</a-typography-paragraph>
							</a-col>
						</a-row>
					</a-col>
					<a-col :span="12">
						<a-row type="flex">
							<a-col>
								<a-typography-paragraph>
									<a-typography-title :level="2">
										{{getScore >= _role['score'] ? '恭喜你成绩及格':'很遗憾，成绩不及格！'}}
									</a-typography-title>
									<a-typography-title :level="2">
										本次成绩{{getScore}}分
									</a-typography-title>
								</a-typography-paragraph>
							</a-col>
						</a-row>
					</a-col>
				</a-row>
				<a-row class="close-panel" :justify="'center'" type="flex" :gutter="[8,4]">
					<a-col :span="7">
						<a-button block @click="$refs.testController.resetError();showStatistical=false">
							错题练习
						</a-button>
					</a-col>

					<a-col :span="7">
						<a-button block @click="$back()">
							退出考试
						</a-button>
					</a-col>
				</a-row>


			</view>
		</view>

		<view class="test-panel">

			<a-row style="width:100%" class="content">
				<a-col :md="3" :lg="3" class="info">
					<a-card style="height: 7vh;">
						<!-- 	<span class="fab-info-title" style="width: 50%;">
							联创交规
						</span> -->
						<view style="padding: 24rpx">
							<h3 style="width: 100%;text-align: center;display: inline-block;">
								第01考台
							</h3>
						</view>
					</a-card>
					<a-card bordered class="info-card" style="height:47.5vh;padding:6px;" :loading="userinfo==null">
						<!-- 	<view>
							
						</view> -->
						<a-row type="flex" justify="center" style="width: 100%;">
							<a-col :span="20" class="image-box">
								<image src="../../static/exercise/jjc.jpg" style="width:100%;height:80px"
									mode="heightFix">
								</image>
							</a-col>
						</a-row>
						<view style="background-color: #fff;margin-top:6px;padding:4px 0px 6px 0px">
							<a-row>
								<a-col>
									<h3>考试信息</h3>
								</a-col>
							</a-row>
							<a-row v-for="(item,index) in infolist" style="width: 100%;">
								<a-col :span="24" style="padding:2px;">
									<a-typography-text>
										{{item[0]}}:
									</a-typography-text>

									<a-typography-text style="margin-left: 18rpx">
										<template v-if="item[1]!='gender'">
											<div class="card-box ant-card-bordered">
												{{userinfo[item[1]]}}
											</div>
										</template>
										<template v-else>

											<div class="card-box ant-card-bordered">
												{{genderText[userinfo[item[1]]]}}
											</div>
										</template>
									</a-typography-text>
								</a-col>
							</a-row>
						</view>

					</a-card>
					<!-- 	<view class="cust-diver">
					</view> -->
					<a-card bordered class="info-card" style="height: 9vh!important;padding:0px;">
						<a-typography-text>
							已用时间:
						</a-typography-text>
						<!-- 		<uni-countdown ref='countdownRef' @getTimeStr="getEndTime" @timeup="submit(true,'timerend')" :show-day="false"
							:hour="0" :minute="45" :second="0" /> -->
						<cus-countdown ref="testTiemsCp" :showDay="false" :hour="0" :minute="0" :second="1">
						</cus-countdown>
					</a-card>
				</a-col>
				<a-col :md="13" :lg="13" class="controller">
					<a-skeleton active :loading="!quelist.length"></a-skeleton>
					<block v-if="quelist.length>0">
						<testMockrealController ref="testController" :getTestTime="endTimes" :needCache="nothisotry"
							@submit="onSubmitTest" :useCacheAns="last" v-model:rightNum="rightNum" :ans="cur_ans"
							:ansArr="qs_ans_arr" v-model:errorNum="errorNum" :scoreRole="_role" :action="action"
							:quesctionlist="quelist" @changeStatus="changeStatus"
							:controllerStatus="controllerStatusMap" @removeQueslist="removeQs" @updatelist="updateList"
							v-model:currentIndex="cur_qs_index">
						</testMockrealController>
					</block>
				</a-col>
				<a-col :md="9" :lg="8" class="qs-table-box ant-card-bordered">
					<a-skeleton active :loading="!quelist.length">
					</a-skeleton>


					<view class="box-content">
						<a-row style="width: 100%;height: 80rpx;max-height: 80rpx;">
							<a-col style="width: 10%;">
								<span class="th-head" style="font-size: 24rpx;">题目</span>
							</a-col>

							<a-col style="width: 90%;">
								<view style="width: 100%;" class="grid">
									<view class="grid-item" v-for="(item) in 10">
										{{item}}列
									</view>
								</view>
							</a-col>


						</a-row>

						<a-row class="change-box">
							<a-col style="width: 10%;max-height: 80rpx;height: 80rpx;">
								<span class="th-head" v-for="(item,index) in getColumn">
									{{item}}行
								</span>
							</a-col>
							<a-col style="width: 90%;"
								:style="{maxHeight:(80*getColumn)+'rpx',height:(80*getColumn)+'rpx'}">
								<view style="width: 100%;" class="grid">
									<view v-for="(i,d) in quelist" class="grid-item"
										@click="()=>$refs.testController.skipQs(d)" :class="{
															'color-change':cur_qs_index==d,
															'color-default':cur_qs_index!=d,
															
														}">

										<span class="fabinfo" :class="{
												'mineFont':i.q_type==1,'maxFont':i.q_type==2,
												'color-error': i.isright === false,
												'color-right': i.isright === true
											}">
											{{i.ansLabel}}
										</span>
									</view>
								</view>
							</a-col>
						</a-row>
					</view>
				</a-col>
			</a-row>
		</view>
	</view>
</template>

<script>
	import testMockrealController from '@/components/test-mockreal-controller/test-mockreal-controller.vue';
	import {
		mapState,
		mapGetters
	} from "vuex"
	import config from '@/admin.config.js'
	import {
		toRaw
	} from "vue";

	const db = uniCloud.database()
	const cmd = db.command
	export default {
		components: {
			testMockrealController,
		},
		data() {
			return {
				tempRight: 0,
				tempError: 0,
				showSubmitTips: false,
				balanceTimer: 10,
				balanceTimerWork: null,
				last_index: 0,
				submitFlag: false,
				endTimes: null,
				errorScore: 0,
				realScore: 0,
				list: [{
					name: '1',
					id: 1
				}, {
					name: '2',
					id: 2
				}],
				showStatistical: false,
				showVideo: false,
				time: 0,
				localTimeStr: '',
				timeTaskId: null,
				cur_ans: [],
				qs_ans_arr: {},
				rightNum: 0,
				errorNum: 0,
				cur_qs_index: 0,
				userinfo: null,
				infolist: [
					['姓名', 'studentName'],
					['性别', 'gender'],
					['科目', 'subject'],
					['车型', 'drive']
				],
				genderText: {
					0: '未知',
					1: '男',
					2: '女'
				},
				controllerStatusMap: {},

				controllerStatus: [{
						status: true,
						title: "显示答案",
						key: "SHOW_ANS",
					},
					{
						status: true,
						title: "显示对错",
						key: "SHOW_RIGHT_OR_ERR"
					},
					{
						status: false,
						title: "显示讲解",
						key: "SHOW_EXPLAN"
					},
					{
						status: false,
						title: "语音讲解",
						key: "SOUND_EXPLAN"
					},
					{
						status: true,
						title: "语音提示",
						key: "SOUND_RIGHT_OR_ERR"
					},
					{
						status: false,
						title: "语音读题",
						key: "SOUND_QS"
					},
					{
						status: false,
						title: "答错自动语音讲解",
						key: "SOUND_ON_ERR"
					},
					{
						status: true,
						title: "手动翻页",
						key: "TURN_PAGE"
					},
					{
						status: false,
						title: "自动翻页",
						key: "AUTO_PAGE"
					},
					{
						status: false,
						title: "答对翻页",
						key: "RIGHT_PAGE"
					}
				],
				quelist: [],
				labelAns: {
					'0': 'A',
					'1': 'B',
					'2': 'C',
					'3': 'D',
					'4': 'E',
					'5': 'F'
				},
				AnsOfLable: {
					'A': '0',
					'B': '1',
					'C': '2',
					'D': '3',
					'E': '4',
					'F': '5',
				},
				action: 'NORMAL',
				message: ['AUTO_PAGE', 'TURN_PAGE', 'RIGHT_PAGE'],
				subject_page_title: '',
				test_page_title_list: [],
				category: false,
				mode: 'CUSTOM',
				drive: '',
				subject: '',
				_role: {},
				showans: false,
				q_type_map: {
					0: 'radio',
					1: 'multiple',
					2: 'judge'
				},
				nowDate: null,
				timeTaskUpDate: null,
				label: ['A', 'B', 'C', 'D', 'E', 'F'],
				textInfo: {
					"0": {
						"value": 0,
						"text": "单选",
						"color": "#0533fc",
						"label": ['A', 'B', 'C', 'D', 'E', 'F'],
						"tips": "提示操作：单选题",
						"getAns": function(cur_qs) {
							if (cur_qs.realProps) {
								return [cur_qs.realProps.realAns]
							} else {
								return '出现异常，联系管理员CODE:7701'
							}
						},
						labelAns: {
							'0': 'A',
							'1': 'B',
							'2': 'C',
							'3': 'D',
							'4': 'E',
							'5': 'F'
						}
					},
					"1": {
						"value": 1,
						"text": "多选",
						"color": "#ff0000",
						"label": ['A', 'B', 'C', 'D', 'E', 'F'],
						"tips": "提示操作：多项选择题",
						"getAns": function(cur_qs) {
							if (cur_qs.realProps) {
								return cur_qs.realProps.realAns.split('|')
							} else {
								return '出现异常，联系管理员CODE:7702'
							}
						},
						labelAns: {
							'0': 'A',
							'1': 'B',
							'2': 'C',
							'3': 'D',
							'4': 'E',
							'5': 'F'
						},
					},
					"2": {
						"value": 2,
						"text": "判断",
						"color": "#000000",
						"label": ['√', '×'],
						"tips": "提示操作：判断选择题",
						"getAns": function(cur_qs) {
							let label = {
								'A': '√',
								'B': '×'
							}
							return [label[cur_qs.q_ans]]
						},
						labelAns: {
							'0': '√',
							'1': '×',
						},
					},
				},
				nothisotry: true,
				last: false
			}
		},
		onLoad(options) {
			//ces
			// this.last = true 
			if (options.d) {
				this.drive = options.d
				this.subject = options.s
			}

			this.userinfo = uni.getStorageSync('testpage')

			if (options.last) {
				this.last = options.last
				this.getQlist()
				for (let s of this.controllerStatus) {
					let {
						status,
						key
					} = s

					this.controllerStatusMap[key] = status
				}
				return
			}

			// if (this.userinfo.last) {
			// 	this.last = true
			// }
			if (this.userinfo.action) {
				this.action = this.userinfo.action
			}
			if (this.userinfo.category) {
				//	console.log(JSON.stringify(this.userinfo))
				this.category = new Boolean(this.userinfo.category)
			}
			if (this.userinfo.model) {
				this.model = this.userinfo.model
			}

			for (let s of this.controllerStatus) {
				let {
					status,
					key
				} = s

				this.controllerStatusMap[key] = status
			}
			this.nowDate = new Date()
			// this.timeTaskUpDate = setInterval(function() {
			// 	self.nowDate = new Date();
			// }, 1000)
		},
		computed: {
			...mapGetters({
				isLogin: 'user/isTokenValid'
			}),
			...mapState('user', ['mechanismName']),
			getColumn() {
				let size = this.quelist.length / 10
				if (size % Math.floor(this.quelist.length / 10) == 0) {
					return size
				} else {
					return Math.floor(this.quelist.length / 10) + 1
				}
			},
			getScore() {
				return this.realScore
			},
			getNow() {
				let date = this.nowDate

				// 获取时间：时分秒
				const hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours()
				const minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()
				const secound = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds()
				// 获取日期：年月日
				const year = date.getFullYear()
				const month = date.getMonth() + 1
				const day = date.getDate()

				// 获取星期几
				const weeks = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");
				const nowWeek = weeks[new Date().getDay()];
				return `${year}年${month}月${day} ${nowWeek} ${hour}:${minute}:${secound}`
			}
		},
		watch: {
			rightNum(nv) {
				console.log('r_nv', nv)
				const self = this
				console.log('on parent=>', self.quelist[this.cur_qs_index])
				const qtype = self.quelist[this.cur_qs_index].q_type
				let sc = self.q_type_map[qtype]
				self.realScore += self._role[sc]

			},
			errorNum(nv) {
				const self = this
				console.log('e_nv', nv)
				console.log('on parent=>', self.quelist[self.cur_qs_index])
				const cur_qs = self.quelist[self.cur_qs_index]
				if (cur_qs.showAns || cur_qs.showAns === true) {
					const qtype = self.quelist[self.cur_qs_index].q_type
					let sc = self.q_type_map[qtype]
					self.errorScore += self._role[sc]
					self.showans = true
				}

				//强制分数交卷功能
				// if (this._role.maxscore - this.errorScore < this._role.score) {
				//   this.submit(true)
				// 	return
				// }

			},
			cur_qs_index(nv, ov) {
				//console.log(nv)
			},
			last_index(nv) {
				//console.log(nv)
			},
			showans(nv) {
				if (nv) {
					//	console.log('startwork')
					this.balanceTimerWork = setInterval(() => {
						this.balanceTimer--
						if (this.balanceTimer <= 0) {
							clearInterval(this.balanceTimerWork)
							this.showans = false
							this.balanceTimer = 10
							this.balanceTimerWork = null
						}
					}, 1000)
				}
				if (nv == false && this.balanceTimerWork) {
					clearInterval(this.balanceTimerWork)
					this.balanceTimer = 10
					this.balanceTimerWork = null
				}
			}
		},
		onUnload() {
			console.log('unmount')
			if (this.timeTaskId) {
				clearInterval(this.timeTaskId)
			}
			if (this.timeTaskUpDate) {
				clearInterval(this.timeTaskUpDate)
			}
			// if (this.submitFlag == false) {
			// 	console.log('call save')
			// this.getEndTime()
			try {
				this.$refs.testController.saveCache(this.realScore)
			} catch (e) {
				console.log(e)
			}
			// }
			// if (this.$refs.countdownRef.timer) {
			// 	clearInterval(this.$refs.countdownRef.timer)
			// }
			if (this.$refs.testTiemsCp.timer) {
				clearInterval(this.$refs.testTiemsCp.timer)
			}
			// uni.setStorageSync('role', this._role)
			// uni.setStorageSync('qlist', this.quelist)
		},
		onReady() {
			this.getQlist()
			// this.$set(this,'rightNum',this.tempRight) 
			// this.$set(this,'errorNum',this.tempError)
			console.log('errpr num', this.tempError)
		},
		onShow() {

			this.checkToken()
			// if(!this.isLogin){
			// 	uni.showModal({
			// 	    content: '登录状态失效，请重新登录',
			// 	    showCancel: false,
			// 	    success() {
			// 	        uni.reLaunch({
			// 	            url: config.login.url
			// 	        })
			// 	    }
			// 	})
			// }
		},
		methods: {
			updateList({
				index,
				obj
			}) {
				const self = this
				console.log(index, obj)
				this.$set(this.quelist, index, obj)
				this.$nextTick(() => {
					console.log('on parent update=>', this.quelist[index])
				})
			},
			checkToken() {
				const self = this
				uniCloud.callFunction({
					name: 'uni-id-sign-cf',
					data: {
						action: 'checkToken'
					}
				}).then(res => {
					if (res.result.code === 30202) {
						uni.showModal({
							content: '登录状态失效，请重新登录',
							showCancel: false,
							success() {
								uni.reLaunch({
									url: config.login.url
								})
							}
						})
					} else {
						if (self.isLogin) {
							//	self.getUserInfo()
						} else {
							if (!self.isLogin) {
								uni.showModal({
									content: '登录状态失效，请重新登录',
									showCancel: false,
									success() {
										uni.reLaunch({
											url: config.login.url
										})
									}
								})
							}
						}
					}
					console.log(res)
				})
			},
			setTestStaticStatus() {
				this.showSubmitTips = false
				this.submit()
			},
			onSubmitTest() {
				this.showSubmitTips = true
			},
			getEndTime() {
				const useTimes = {
					h: this.$refs.testTiemsCp.h,
					i: this.$refs.testTiemsCp.i,
					s: this.$refs.testTiemsCp.s,
				}
				this.endTimes = useTimes
				return useTimes
			},
			submit(forced = false, form = 'submit') {

				try {
					console.log('从这里来')
					this.submitFlag = true
					const self = this
					const useTimes = this.getEndTime()
					const score = this.realScore

					const a = {
						maxscore: this._role['score'],
						score: score,
						q: this.quelist,
						en: this.errorNum,
						rn: this.rightNum,
						er: this.$refs.testController.qs_ans_arr
					}
					console.log('规则', this._role)
					let dateObj = new Date()
					let username = uni.getStorageSync('lastUsername')
					let formdata = {
						error_num: this.errorNum,
						right_num: this.rightNum,
						score: this.realScore,
						form: form,
						username: username,
						create_date: dateObj.toLocaleString()
					}

					// console.log('submitlog',formdata)
					// console.log(this._role.maxscore, this.errorScore, this._role.score)
					// console.log(this._role.maxscore - this.errorScore < this._role.score)
					self.nothisotry = false
					uni.setStorageSync('mocktestinfo', a)
					uni.setStorageSync('usetimes', useTimes)
					uni.setStorageSync('score', score)
					self.$topage('/pages/exercise/mocktestscore', {}, 'close')

					return
					if (!forced) {
						uni.showModal({
							content: '是否提交试卷？',
							title: "提示",
							success(res) {

								if (res.confirm) {
									// const logResult = await db.collection('score-log').add(formdata)
									// if (logResult) {
									// 	//console.log('score-log')
									// }
									self.nothisotry = false
									uni.setStorageSync('mocktestinfo', a)
									uni.setStorageSync('usetimes', useTimes)
									uni.setStorageSync('score', score)
									self.$topage('/pages/exercise/mocktestscore', {}, 'close')
									// uni.redirectTo({
									// 	url: '/pages/exercise/errorlist'
									// })
									//await self.$refs.testController.saveCache(false)
									// self.$topage('/pages/exercise/errorlist', {}, 'close')

								}
							}
						})

					} else {
						uni.showModal({
							content: '当前成绩不及格，即将交卷!错题:' + this.errorNum + '个!',
							title: "提示",
							success(res) {
								self.nothisotry = false
								uni.setStorageSync('mocktestinfo', a)
								uni.setStorageSync('usetimes', useTimes)
								uni.setStorageSync('score', score)
								self.$topage('/pages/exercise/mocktestscore', {}, 'close')
								//self.$topage('/pages/exercise/errorlist', {}, 'close')
							}
						})

					}
				} catch (e) {
					uni.showToast({
						title: '1103' + e,
						duration: 5000,
						icon: 'error'
					})
				}

			},
			getChangeAns() {
				//	console.log('当前错题INDEX',this.cur_qs_index)
				let arr = []
				this.quelist[this.cur_qs_index].q_struct.forEach((e, i) => {
					if (this.$refs.testController.getCurChangeAns().includes(e.index)) {
						arr.push(this.textInfo[this.quelist[this.cur_qs_index].q_type]['labelAns'][`${i}`])
					}
				})
				return arr
			},

			getGender(item) {
				return this.genderText[this.userinfo[item]]
			},
			removeQs(removeIndexList) {

				this.quelist = this.quelist.filter((e) => {
					return removeList.includes(e.s_id) ? false : e
				})

				// for (let s of removeIndexList) {
				// 	//	console.log(s)
				// 	this.quelist.splice(s, 1)
				// }
			},
			changeStatus(meesageType, status) {
				for (let s of this.message) {
					if (s === meesageType) {
						this.controllerStatusMap[meesageType] = status
						this.setKeyStatus(s, true)
					} else {
						this.controllerStatusMap[s] = false
						this.setKeyStatus(s, false)
					}
				}
			},
			setKeyStatus(key, status) {
				for (let s of this.controllerStatus) {
					if (s.key === key) {
						s.status = status
						return
					}
				}
			},
			//e.target.checked/
			onControllerStatusChange(e) {
				this.controllerStatusMap[e.target.value] = e.target.checked
			},
			startTimes() {
				// this.time++
				// if(this.time)
			},
			shuffle(arr) {
				var l = arr.length
				var index, temp
				while (l > 0) {
					index = Math.floor(Math.random() * l)
					temp = arr[l - 1]
					arr[l - 1] = arr[index]
					arr[index] = temp
					l--
				}
				return arr
			},
			resort(struct, s_ans) {

				let arr = []
				let n_ans = [] //重置后的答案
				let s_ans_arr = s_ans.split('|') //重置前答案
				let s_ans_index = []
				for (let s of s_ans_arr) {
					s_ans_index.push(parseInt(this.AnsOfLable[s]))
				}

				struct.forEach((e, i) => {
					if (s_ans_index.includes(e.index)) {
						arr.push(i)
						n_ans.push(this.labelAns[`${i}`])
					}
				})
				return {
					realAns: n_ans.join('|'),
					realIndex: arr.join(',')
				}

			},
			async getLastCache() {
				const uid = uni.getStorageSync('userinfo')._id
				const result = await db.collection('test-history')
					.where({
						user_id: cmd.eq(uid)
					}).limit(1)
					.get()
				if (result.result.data.length > 0) {
					return result.result.data
				} else {
					uni.showToast({
						title: "缓存失效请重新练习!",
						duration: 2000,
						icon: "error"
					})
					return false
				}
			},
			async getQlist() {


				let qlstore = null;
				let qsAns = []
				let ql = []
				let qlClone = []
				let subjectName = '仿真考试'
				let paper = null
				let test = null
				let paperlist = null
				let sortMap = {
					2: [],
					0: [],
					1: []
				}
				let index = 0
				this.subject_page_title = subjectName
				// this.quelist = uni.getStorageSync('qlist')
				// this._role = uni.getStorageSync('role')
				// return
				if (this.last) {

					const cacheReuslt = await this.getLastCache()
					cacheReuslt[0].cachedata = JSON.parse(cacheReuslt[0].cachedata)

					// this.rightNum =0
					// this.errorNum =0
					// this.cur_qs_index = 0
					// this.qs_ans_arr = [] 

					// this.quelist =uni.getStorageSync('qlist')
					// this.cur_ans = this.quelist[0]

					// console.log('huan cun')
					// return 
					console.log('cachedata=>', cacheReuslt[0].cachedata.ans)
					if (cacheReuslt) {
						//	console.log(cacheReuslt)
						// // cacheReuslt[0].qlist
						const self = this
						this.tempRight = cacheReuslt[0].cachedata.r_num
						this.tempError = cacheReuslt[0].cachedata.e_num
						// setTimeout(()=>{
						// 	this.rightNum = this.tempRight
						// 	this.errorNum = this.tempError 
						// },3000)
						this._role = cacheReuslt[0].role
						this.realScore = cacheReuslt[0].cachedata.score
						this.cur_qs_index = cacheReuslt[0].cachedata.cur_index
						this.qs_ans_arr = cacheReuslt[0].cachedata.ans
						this.cur_ans = cacheReuslt[0].cachedata.cur_ans
						this.quelist = cacheReuslt[0].cachedata.qlist

						this.$nextTick(() => {
							self.rightNum = cacheReuslt[0].cachedata.r_num
							self.errorNum = cacheReuslt[0].cachedata.e_num
						})
						// uni.setStorageSync('qlist', this.quelist)
						uni.setStorageSync('role', this._role)
					}
					return
				}
				const self = this
				const formParams = {
					drive: this.drive,
					subject: this.subject,
					ACTION: 'getMockData'
				}

				const testRoleInfo = await db.collection('test-role').where({
						type_drive_id: db.command.eq(this.drive),
						type_subject_id: db.command.eq(this.subject)
					}).limit(1)
					.get()
				if (testRoleInfo.result.data.length > 0) {
					this._role = testRoleInfo.result.data[0]
					const roleItem = await db.collection('role-item').where({
						_id: db.command.in(this._role.role_item_ids)
					}).get()
				}

				uniCloud.callFunction({
					name: 'wyquesction',
					data: formParams,
					success(res) {
						//console.log('result=>', res)
						self.quelist = res.result.data
						uni.setStorageSync('qlist', self.quelist)
						uni.setStorageSync('role', self._role)
						let i = 0
						// for (let s of self.quelist) {
						// //	console.log(i++, s.q_ans)
						// }
					}
				})

				return

				// const testRoleInfo = await db.collection('test-role').where({
				// 		type_drive_id: db.command.eq(this.drive),
				// 		type_subject_id: db.command.eq(this.subject)
				// 	}).limit(1)
				// 	.get()
				// if (testRoleInfo.result.data.length > 0) {
				// 	this._role = testRoleInfo.result.data[0]
				// 	const roleItem = await db.collection('role-item').where({
				// 		_id: db.command.in(this._role.role_item_ids)
				// 	}).get()
				// 	let quesliteTemp = []
				// 	let q_type = {
				// 		'radio': 0,
				// 		'multiple': 1,
				// 		'judge': 2
				// 	}
				// 	for (let s of roleItem.result.data) {
				// 		let tempdata = await db.collection('test-paper')
				// 			.where({
				// 				s_id: cmd.eq(s.test_paper_id)
				// 			})
				// 			.field({
				// 				_id: true,
				// 				name: true,
				// 				quesction_list: true,
				// 				s_id: true,
				// 			})
				// 			.limit(1)
				// 			.get()
				// 		for (let r of ['radio', 'multiple', 'judge']) {
				// 			if (s[r] > 0) {
				// 				const dt = await db.collection('quesction').aggregate()
				// 					.match({
				// 						s_id: cmd.in(tempdata.result.data[0].quesction_list),
				// 						q_type: cmd.eq(q_type[r])
				// 					})
				// 					.sample({
				// 						size: s[r]
				// 					}).limit(s[r]).end()
				// 				for (let sq of dt.result.data) {
				// 					sq.infoname = subjectName
				// 					if (sq.q_type != 2) {
				// 						sq.q_struct = this.shuffle(sq.q_struct)
				// 						sq.realProps = this.resort(sq.q_struct, sq.q_ans)
				// 					}
				// 					if (sq.q_type == 1) {
				// 						sq.check = [false, false, false, false, false, false]
				// 					}
				// 					ql.push(sq)
				// 					sortMap[sq.q_type].push(index)
				// 					index++
				// 				}
				// 			}
				// 		}
				// 	}
				// 	for (let j of sortMap[2]) {
				// 		qlClone.push(ql[j])
				// 	}
				// 	for (let j of sortMap[0]) {
				// 		qlClone.push(ql[j])
				// 	}
				// 	for (let j of sortMap[1]) {
				// 		qlClone.push(ql[j])
				// 	}
				// 	this.quelist = qlClone
				// 	uni.setStorageSync('qlist', this.quelist)
				// }
				// return
			}
		}
	}
</script>

<style scoped lang="scss">
	@import url('./mockrealexercis.css');
</style>
